package com.mingqijia.gassafety.job.service.mbp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gap.basic.exception.BizException;
import com.google.common.base.Joiner;
import com.mingqijia.gassafety.job.service.CompanyService;
import com.mingqijia.gassafety.shared.constant.UrlConst;
import com.mingqijia.gassafety.shared.dto.tcis.CancelBusiOrderDTO;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.shared.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName EquipmentCmpService.java
 * @createTime 2022年08月08日
 */
@Component
@Slf4j
public class TcisService {

    @Value(value = "${gassafety.warnStrategy.openUrl}")
    public String targetUrl ;

    @Value(value = "${gassafety.tcis.openAppId}")
    public String openId;

    @Value(value = "${gassafety.tcis.openAppSecret}")
    public String openSecret ;

    @Autowired
    CompanyService companyService;

    /**
     * TCIS同步
     *
     * @param jsonData 请求体数据
     * @param type     请求接口：0 工商户用气设备 1外购燃气具安装
     *                 2外购燃气具维修  3报警器信息记录查询  4工单详情查询
     * @param param
     * @return ｛code ，msg ，data｝ code 0成功 -1失败
     */
    public Map<String, Object> tcisRequest(Map<String, Object> jsonData, int type,
                                           String param ,String spId,String consumerId) {
        String orgCode = companyService.getOrgCode(spId,consumerId);

        log.info("TcisService——tcisRequest,主要发送数据：{},type：{},param:{}",
                JSONObject.toJSONString(jsonData), type, param);
        if (StringUtils.isEmpty(param)) param = "";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", -1);
        resultMap.put("msg", "tcis请求失败");
        JSONObject jsonObject = null;
        Map<String, Object> params = new HashMap<>();
        if (jsonData != null) {
            params = jsonData;
        }
        params.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
        try {
            String token = getToken();
            log.info("开放平台token：{}", token);
            if (StringUtils.isEmpty(token)) {
                throw new BizException(token + "开发平台token获取失败");
            }
            String jsonStr = openSign(params, openSecret);
            params.put("openSign", jsonStr);
            params.put("data", JSONObject.parse(params.get("data") + ""));
            String url = "";
            int methodType = 0;
            if (type == 0) {
                url = targetUrl + UrlConst.BUSI_GSAPPLIANCE.getUrl()+"?orgCode="+orgCode;
            } else if (type == 1) {
                url = targetUrl + UrlConst.BUSI_OUTHOUSEINSTALL.getUrl() +"?orgCode="+orgCode;
            } else if (type == 2) {
                url = targetUrl + UrlConst.BUSI_OUTHOUSEREPAIR.getUrl()+"?orgCode="+orgCode;
            } else if (type == 3) {
                methodType = 3;
                url = targetUrl + UrlConst.QUERY_ALARMAPPLIANCE.getUrl() + param+"&orgCode="+orgCode;
            } else if (type == 4) {
                url = targetUrl + UrlConst.QUERY_ORDERDETAIL.getUrl()+"?orgCode="+orgCode;
            }
            //测试阶段 固定orgCode= ZB01
            log.info("TcisService——requestUrl：{}", url);
            String body = HttpUtil.getBody(JSONObject.toJSONString(params), url, "", null, methodType, token);
            log.info("TcisService——body,响应结果body：{}",
                    JSONObject.toJSONString(body));
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null || jsonObject.get("result") == null) return resultMap;
            if (Integer.parseInt(jsonObject.get("result") + "") == 0) {
                resultMap.put("data", jsonObject.get("body"));
                resultMap.put("code", 0);
            }
            resultMap.put("msg", jsonObject.get("msg"));
        } catch (Exception e) {
            log.error("TcisService-error:{}", e);
            throw e;
        }
        return resultMap;
    }

    public static String openSign(Map<String, Object> map, String... keys) {
        log.info("sign map = [{}],keys = [{}]", map.toString(), keys);
        Map<String, Object> treeMap = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
        // 排序
        treeMap.putAll(map);
        List<String> params = new ArrayList<>(treeMap.size());
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            if ("openSign".equals(entry.getKey())) {
                continue;
            }
            StringBuilder sb = new StringBuilder();
            sb.append(entry.getKey()).append("=");
            Object value = entry.getValue();
            if (value instanceof JSONObject) {
                sb.append(((JSONObject) value).toString(SerializerFeature.WriteMapNullValue));
            } else if (value instanceof JSONArray) {
                sb.append(((JSONArray) value).toString(SerializerFeature.WriteMapNullValue));
            } else {
                sb.append(String.valueOf(value));
            }
            params.add(sb.toString());
        }
        String signStr = Joiner.on("&").join(params);
        StringBuilder keySb = new StringBuilder();
        keySb.append(signStr);
        for (String key : keys) {
            keySb.append(key);
        }
        log.info("sb = [{}],MD5 SB=[{}]", keySb.toString(), MD5Util.encrypt(keySb.toString()).toUpperCase());
        return MD5Util.encryptUpper(keySb.toString());
    }

    public String getToken() {
        String token = "";
        Map<String, Object> params = new HashMap<>();
        params.put("openAppId", openId);
        params.put("openAppSecret", openSecret);
        try {
            String body = HttpUtil.getBody(JSONObject.toJSONString(params),
                    targetUrl + UrlConst.OPEN_TOKEN.getUrl(), "", "");
            if (StringUtils.isEmpty(body)) return null;
            log.info("getToken-response:{}", body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (Integer.parseInt(jsonObject.getString("code")) == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                token = data.getString("token");
            }
        } catch (Exception e) {
            log.error("getToken-error:{}", e);
            return null;
        }
        return token;
    }

    public void tcisRequestCancelBusiOrder(CancelBusiOrderDTO request, String consumerId, String spId) {
        String orgCode = companyService.getOrgCode(spId, consumerId);
        log.info("TcisService——tcisRequest,主要发送数据：{},consumerId:{}", JSONObject.toJSONString(request), consumerId);
        Map<String, Object> params = new HashMap<>();
        params.put("body", request);
        params.put("orgCode", orgCode);
        params.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
        try {
            String token = getToken();
            log.info("开放平台token：{}", token);
            if (StringUtils.isEmpty(token)) {
                throw new BizException(token + "开发平台token获取失败");
            }
            String jsonStr = openSign(params, openSecret);
            params.put("openSign", jsonStr);
            String url = targetUrl + UrlConst.BUSI_CANCELBUSIORDER.getUrl() + "?orgCode=" + orgCode;
            //测试阶段 固定orgCode= ZB01
            log.info("TcisService——requestUrl：{}", url);
            String body = HttpUtil.getBody(JSONObject.toJSONString(params), url, "", null, 0, token);
            log.info("TcisService——body,响应结果body：{}", JSONObject.toJSONString(body));
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null || jsonObject.get("result") == null) {
                throw new BizException("工单取消失败");
            }
            String result = jsonObject.getString("result");
            if ("0".equals(result)) {
                return;
            }
            String msg = jsonObject.get("msg") != null ? jsonObject.getString("msg") : "工单取消同步给TCIS失败";
            throw new BizException(msg);
        } catch (Exception e) {
            log.error("TcisService-error:{}", e);
            throw e;
        }
    }

}

